package com.yh.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yh.service.ConfigService;
import com.yh.service.impl.ConfigServiceImpl;
import com.yh.util.ELTools;

@WebListener
public class SystemListener implements ServletContextListener, HttpSessionListener {

	private Logger log = LoggerFactory.getLogger(this.getClass());
	private long count = 0;// 访问数量
	private int online = 0;// 在线人数

	private ServletContext application;
	private ConfigService service = new ConfigServiceImpl();

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// 每创建一个session就会多一个人在线以及访问次数加一
//		System.out.println("----------------->"+online);
		log.debug("online:{}", online);

		count++;
		online++;
		application.setAttribute("count", count);
		application.setAttribute("online", online);
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		online--;
		application.setAttribute("online", online);
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// 读取之前保存的数量
		count = service.getCount();
		log.debug("count:{}",count);

		application = sce.getServletContext();
		application.setAttribute("count", count);
		application.setAttribute("online", online);

		// 添加一个全局给EL表达式使用的工具对象
		application.setAttribute("t", new ELTools());

		// 全局的FastJSON的配置
//		com.yh.util.FastJSONConfig.getConfig().initConfig();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// 保存现在访问的人数
		service.saveCount(count);
	}

}
